package com.dshore.messagecenter.log;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dshore.messagecenter.dao.system.SysLogDao;


@Aspect
@Component
public class LogAopAction {
	private final Logger logger = LoggerFactory.getLogger(LogAopAction.class);

    @Autowired
    private SysLogDao logDao;
    
   // @Autowired
	//private UALoginConnector uALoginConnector;
    
    /**
     * Before   : 在方法执行前进行切面
     * After	:在方法执行后
     * execution    : 定义切面表达式
     * public * com.eparty.ccp.*.impl..*.*(..)  //路径
     * 
     * public :匹配所有目标类的public方法，不写则匹配所有访问权限
     * 第一个* :方法返回值类型，*代表所有类型 
     * 第二个* :包路径的通配符
     * 第三个..* :表示impl这个目录下所有的类，包括子目录的类
     * 第四个*(..) : *表示所有任意方法名,..表示任意参数
     *      
     *  @annotation //注解     有该注解的方法切入
     */

    /**
     * 记录操作日志
     */
    @AfterReturning(returning="rvt",pointcut="@annotation(com.dshore.messagecenter.log.LogAnnotation)")  // 使用上面定义的切入点
    public void recordLog(JoinPoint joinPoint,Object rvt){
  /*  	//获取返回值
		@SuppressWarnings("unchecked")
		ResponseResult<Object>responseResult=(ResponseResult<Object>) rvt;
    	if(responseResult.getState()==200) {
    		Long start = System.currentTimeMillis();
            SysLog log = new SysLog();
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            //获取对象
            SsoUserInfo sso=UALoginConnector.getUserFromRequest(request);
           // User user = (User) request.getSession().getAttribute("user");
            
            try {
            	 if(sso == null){
                     logger.warn("user 信息为空");
                     log.setUserName("用户  信息为空");
                 }else{
                 	//获得用户信息
                     log.setUserId(sso.getUserId());
                   //取接口对象
                     AppframeOrg appframeorg= AppframeOrgClient.getInstance();
                     User user=appframeorg.getUserById(Long.valueOf(sso.getUserId()));
                     log.setUserName(user.getName());
                 }
            	 
            	//开始获取 日志 值
            		 Map<String,String> map = getLogMark(joinPoint);
            		 String arg="";
            		 //静态参数不用从请求取参
            		 if(StringUtils.isEmpty(map.get("staticArgs"))) {
            			 arg=request.getParameter(map.get("argsName"));
            		 }else {
            					 Object[]args=joinPoint.getArgs();
            					 if(args.length>0){
            						 arg=(String) args[0];
            					 }
            		 }
            		 
                	 log.setCreatedTime(new Date());
                	 if(StringUtils.isEmpty(map.get("tableName"))) {
                		 log.setId(UUIDUtil.getUUId());
                		 log.setContent(map.get("methodType")+map.get("targetType")+" "+arg);
                         logDao.insert(log);
                	 }else {
                		 Object[]ids=arg.split(",");
                		 //根据表名去查数据名称
                		 List<Map<String, Object>>list;
                		 
                		 if(!StringUtils.isEmpty(map.get("thresholdDeletionSpecial"))) {
                			 list=logDao.selectData(ids);
                		 }else {
                			 if(StringUtils.isEmpty(map.get("queryArgs"))) {
                    			 list=logDao.selectData(map.get("tableName"),map.get("fieldName"),ids);
                    		 }else {
                    			 list=logDao.selectData(map.get("tableName"), map.get("fieldName"), map.get("queryArgs"), ids);
                    		 }
                		 }
                		 
                		 System.out.println(list);
                		 if(list!=null) {
                			 for(int i=0;i<list.size();i++) {
                    			 log.setId(UUIDUtil.getUUId());
                    			 if(!StringUtils.isEmpty(map.get("dictType"))) {
                    				 String code=(String)list.get(i).get(map.get("fieldName"));
                    				 String name=logDao.selectDictName(code,map.get("dictType"));
                    				 log.setContent(map.get("methodType")+map.get("targetType")+" "+name);
                    			 }else if(!StringUtils.isEmpty(map.get("thresholdDeletionSpecial"))){
                    				 String[] dicttypes=map.get("thresholdDeletionSpecial").split(",");
                    				 String name="";
                    				 String name1="";
                    				 for(String dicttype:dicttypes) {
                    					 if("monitor_type".equals(dicttype)) {
                        					 name=logDao.selectDictName((String)list.get(i).get("OBJ_TYPE"),"monitor_type");
                        				 } else {
                        					 name1=logDao.selectDictName((String)list.get(i).get("KPI_ID"),"kpi_type");
                        				 }
                    				 }
                    				 log.setContent(map.get("methodType")+map.get("targetType")+" "+name+name1);
                    			 }else {
                    				 log.setContent(map.get("methodType")+map.get("targetType")+" "+list.get(i).get(map.get("fieldName")));
                    			 }
                    			logDao.insert(log);
                    		 }
                		 }
                	 }
            	
            }catch (ClassNotFoundException c){
                logger.error(c.getMessage());
            }catch (Exception e){
            	System.err.println(e);
                logger.error("插入日志异常",e.getMessage());
            }
            Long end = System.currentTimeMillis();
            logger.info("记录日志消耗时间:"+ (end - start) / 1000);
    	}*/
        
    }

    /**
     * 获取日志值
     * @param joinPoint
     * @return
     * @throws ClassNotFoundException
     */
    private Map<String,String> getLogMark(JoinPoint joinPoint) throws ClassNotFoundException {
        Map<String,String> map = new HashMap<>();
        String methodName = joinPoint.getSignature().getName();
        String targetName = joinPoint.getTarget().getClass().getName();
        Class<?> targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods){
            if(method.getName().equals(methodName)){
                LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
                if(logAnnotation!=null) {
                	map.put("targetType",logAnnotation.targetType());
                	map.put("methodType",logAnnotation.methodType());
                	map.put("argsName",logAnnotation.argsName());
                	map.put("tableName",logAnnotation.tableName());
                	map.put("fieldName",logAnnotation.fieldName());
                	map.put("dictType",logAnnotation.dictType());
                	map.put("staticArgs",logAnnotation.staticArgs());
                	map.put("queryArgs",logAnnotation.queryArgs());
                	map.put("thresholdDeletionSpecial",logAnnotation.thresholdDeletionSpecial());
                }
            }
        }
        return map;
    }
    
    

    
}
